package com.deyuanyun.pic.settings.service.pipe.impl;

import com.deyuanyun.pic.common.cache.TempStoreDataSupport;
import com.deyuanyun.pic.common.dto.DTOResult;
import com.deyuanyun.pic.common.exception.ExceptionCode;
import com.deyuanyun.pic.common.exception.ExceptionCodeUtil;
import com.deyuanyun.pic.common.exception.bizcode.basedata.pipe.PipeCrossCodeEnum;
import com.deyuanyun.pic.common.exception.code.ModuleMsg;
import com.deyuanyun.pic.common.util.ObjectUtil;
import com.deyuanyun.pic.settings.controller.dto.PipeLineInfraVO;
import com.deyuanyun.pic.settings.controller.dto.PipeValidateVO;
import com.deyuanyun.pic.settings.controller.dto.ValveRoomDTO;
import com.deyuanyun.pic.settings.domain.pipe.PipeLine;
import com.deyuanyun.pic.settings.domain.pipe.PipeLineElement;
import com.deyuanyun.pic.settings.domain.pipe.PipeLineExample;
import com.deyuanyun.pic.settings.domain.util.DomainInitUtil;
import com.deyuanyun.pic.settings.mapper.pipe.PipeLineElementMapper;
import com.deyuanyun.pic.settings.mapper.pipe.PipeLineMapper;
import com.deyuanyun.pic.settings.mapper.pipe.ValveRoomMapper;
import com.deyuanyun.pic.settings.service.pipe.PipeLineService;
import com.deyuanyun.pic.settings.support.utils.PipeDictUtils;
import com.google.common.collect.Lists;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

@Service
public class PipeLineServiceImpl implements PipeLineService {

	private static Logger log = LogManager.getLogger(PipeLineServiceImpl.class);

	@Resource
	private PipeLineMapper pipeLineMapper;

    @Resource
    ValveRoomMapper valveRoomMapper;
    @Resource(name = "PipeLineElementSettingMapper")
    PipeLineElementMapper pipeLineElementMapper;


	@Override
	public PipeLine selectByPrimaryKey(String id) {
		return pipeLineMapper.selectByPrimaryKey(id);
	}

    @Override
    @Cacheable("tempStoreData")
    public PipeLine selectByPrimaryKeyCache(String id) {
        return pipeLineMapper.selectByPrimaryKey(id);
    }


    @Cacheable("tempStoreData")
    public PipeLine getLineByName(String name) {
        return pipeLineMapper.getLineByName(name);
    }

    /**
	 * 
	 * @创建者:严祥
	 * @创建时间：2015年8月17日
	 * @方法说明:得到所有管线名称
	 * @参数:@return
	 * @return:DTOResult
	 * 
	 */
	@Override
	public DTOResult getPiPelLine() {

		// 定义一个传出状态码
		// 0:表示正常
		// 1:数据库异常
		// 2:没有查询到结果集
		// 3:空指针异常
		String code = "";

		// 定义一个Mapper层返回集合
		List<PipeLine> list = pipeLineMapper.selectAllPipeLine();

		if (null == list) {
			code = ExceptionCodeUtil.getExceptionCode(ModuleMsg.BASE_DATA)
					+ PipeCrossCodeEnum.nullPointer.getCode();
			return new DTOResult(code, PipeCrossCodeEnum.nullPointer.getLable());
		}

		if (list.size() <= 0) {
			code = ExceptionCodeUtil.getExceptionCode(ModuleMsg.BASE_DATA)
					+ PipeCrossCodeEnum.mapperIsNull.getCode();
			return new DTOResult(code,
					PipeCrossCodeEnum.mapperIsNull.getLable());
		}

		code = ExceptionCode.SUCCESS.getCode();
		return new DTOResult(code, ExceptionCode.SUCCESS.getLabel(), list);

	}

	@Override
	public List<PipeLine> getLine() {
		List<PipeLine> pipeLineList= TempStoreDataSupport.pullData("pic_pipeLineList_");
		if (ObjectUtil.isEmptyAll(pipeLineList)){
			pipeLineList=pipeLineMapper.getLine();
			TempStoreDataSupport.pushDataByTimeMinute("pic_pipeLineList_",pipeLineList,30);
		}
		return pipeLineList;
	}

	public List<PipeLine> selectByCondition(PipeLineInfraVO pipeLineInfraVO) {
		return pipeLineMapper.selectByCondition(pipeLineInfraVO);
	}

	public boolean validateRepByline(PipeValidateVO pipeValidateVO) {
		int n = pipeLineMapper.validateRepByline(pipeValidateVO);
		return n == 0 ? false : true;
	}

    /**
     * 清空管道缓存
     * @param
     * @return
     * @author axiao(xj08.dream@gmail.com)
     * @date 2016-11-18
     */
    private void clearPipeLineCache() {
        TempStoreDataSupport.removeData(PipeDictUtils.PIPEDICTUTILS_PIPELINEBIMAP);
        TempStoreDataSupport.removeData(PipeDictUtils.PIPEDICTUTILS_PIPELINEMAP);
        TempStoreDataSupport.removeData("pic_pipeLineList_"); //todo 坑
    }


    public int deleteLineByIds(String[] ids) {
        PipeLineExample lineExample = new PipeLineExample();
        lineExample.createCriteria().andIdIn(Arrays.asList(ids));
        List<PipeLine> lines = pipeLineMapper.selectByExample(lineExample);
        List<String> deleteLine = new ArrayList<String>();
        for (PipeLine line : lines) {
            if(!"20".equals(line.getDataStated())) {
                deleteLine.add(line.getId());
            }
        }
		int n = pipeLineMapper.deleteLineByIds(ids);
        if(!deleteLine.isEmpty())
            pipeLineElementMapper.deleteVRElement(deleteLine);
        if(n > 0) {
            clearPipeLineCache();
        }
        return n;
	}

	public int updateStatus(String[] ids) {
		int n = pipeLineMapper.updateStatus(ids);
        if(n > 0) {
            clearPipeLineCache();
        }
        return n;
	}

	public int updateLineS(String[] ids, String status) {
		int n = pipeLineMapper.updateLineS(ids, status);
        if(n > 0) {
            clearPipeLineCache();
        }
        return n;
	}

    @Override
    public void insertPipeLineInfo(String lineName, String lineAbridge, String[] rvIds) {
        PipeLine pipeLine = new PipeLine();
        DomainInitUtil.initCreateDomain(pipeLine);
        pipeLine.setDataStated("03");
        pipeLine.setState((short)1);
        pipeLine.setShowName(lineName);
        pipeLine.setName(lineName);
        pipeLine.setAbridge(lineAbridge);
        pipeLineMapper.insertSelective(pipeLine);//新增管道信息

        if(rvIds != null) {
            insertVavleRoom(pipeLine.getId(), Arrays.asList(rvIds));
        }
    }
    
    /**
     * 新增管道下的场站阀室要素
     * @param pipelineId 管道id
     * @param ids 场站阀室id
     * @return
     * @author axiao(xj08.dream@gmail.com)
     * @date 2016-09-03
     */
    private void insertVavleRoom(String pipelineId, List<String> ids) {
        if(ids != null) {
            for (String rvId : ids) {
                ValveRoomDTO valveRoomDTO = valveRoomMapper.selectByPrimaryKey(rvId);
                PipeLineElement pipeLineElement = new PipeLineElement();
                pipeLineElement.setElementType("VALVEROOM");
                pipeLineElement.setPipeLineId(pipelineId);
				DomainInitUtil.initCreateDomain(pipeLineElement);
                pipeLineElement.setElementId(valveRoomDTO.getId());
                pipeLineElement.setElementName(valveRoomDTO.getShowName());
                pipeLineElementMapper.insertSelective(pipeLineElement); //新增管道场站阀室要素信息
            }
        }
    }

    @Override
    public void updatePipeLineInfo(PipeLineInfraVO pipeLineInfraVO, String[] rvIds) {
        String lineId = pipeLineInfraVO.getId();
        PipeLine pipeLine = new PipeLine();
        pipeLine.setId(lineId);
        pipeLine.setName(pipeLineInfraVO.getLineName());
        pipeLine.setShowName(pipeLineInfraVO.getLineName());
        pipeLine.setAbridge(pipeLineInfraVO.getLineAbridge());
        DomainInitUtil.initUpdateDomain(pipeLine);
        pipeLineMapper.updateByPrimaryKeySelective(pipeLine);//更新管道信息

        if (rvIds != null) {
            List<String> rvIdList = Lists.newArrayList(rvIds);
            List<String> deleteAfterVIds = pipeLineElementMapper.queryValveRoomsIdString(lineId); //得到未编辑之前的所有场站阀室id集合信息
            Iterator<String> it = rvIdList.iterator();
            while (it.hasNext()) {
                String rvId = it.next();
                if (deleteAfterVIds.contains(rvId)) {//当选择的场站阀室id 在 未删除中的id存在的时候， 直接删除，剩下的就是需要直接逻辑删除的
                    deleteAfterVIds.remove(rvId);
                    it.remove(); //删除不需要进行新增操作的场站阀室id
                }
            }
            if (!deleteAfterVIds.isEmpty()) {
                pipeLineElementMapper.updateVRElementByIds(lineId, deleteAfterVIds);//逻辑删除用户取消选择的场站阀室
            }

            insertVavleRoom(lineId, rvIdList); //剩下的就是需要新增的管道对应的要素
        }
        clearPipeLineCache();
    }
}
